package top.codef.secure.handlers;

import java.io.IOException;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import com.fasterxml.jackson.databind.ObjectMapper;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import top.codef.secure.pojomodel.SecureResponseEnum;

public class CerberusSessionInformationExpiredStrategy implements SessionInformationExpiredStrategy {

	private final ObjectMapper objectMapper;

	public CerberusSessionInformationExpiredStrategy(ObjectMapper objectMapper) {
		this.objectMapper = objectMapper;
	}

	@Override
	public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
		HttpServletResponse httpServletResponse = event.getResponse();
		httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
		httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
		httpServletResponse.getWriter().write(
				objectMapper.writeValueAsString(SecureResponseEnum.ACCESS_DENIED.createSecureModel("用户验证异常，请重新登录")));
	}

}
